import { Button, Form, FormInstance, Input, Select, Space } from 'antd';
import { forwardRef } from 'react';

interface FormGeneratorProps {
  config: FormConfigItem[];
  // 函数接收一个value
  onFinish?: (values: any) => void;
  // 函数无参数
  onReset?: () => void;
  values?: any;
  // 移除原有的ref定义（由forwardRef自动处理）
  // ref?: any;
  isDialog?: boolean;
  confirmText?: string;
  resetText?: string;
}

// const SearchForm: React.FC<FormGeneratorProps> = forwardRef(
const SearchForm = forwardRef<FormInstance, FormGeneratorProps>(
  (
    {
      config,
      onFinish,
      onReset,
      values,
      isDialog = true,
      confirmText = '查询',
      resetText = '重置',
    },
    ref,
  ) => {
    const renderFormItem = (item: FormConfigItem) => {
      switch (item.type) {
        case 'input':
          return <Input placeholder={item.placeholder} />;
        case 'select':
          return (
            <Select placeholder={item.placeholder}>
              {item.options?.map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          );
      }
    };
    return (
      <Form className='layout_form' ref={ref} onFinish={onFinish} onReset={onReset}>
        {config.map((item) => (
          <Form.Item key={item.name} label={item.label} name={item.name}>
            {renderFormItem(item)}
          </Form.Item>
        ))}
        {isDialog && (
          <Form.Item>
            <Space>
              <Button type='primary' htmlType='submit'>
                {confirmText}
              </Button>
              <Button htmlType='reset'>{resetText}</Button>
            </Space>
          </Form.Item>
        )}
      </Form>
    );
  },
);

export default SearchForm;
